package org.softmed.rest.admin.aop.manager;

import java.util.ArrayList;
import java.util.List;

import org.softmed.persistence.PersistenceManager;
import org.softmed.persistence.PersistenceManagerProvider;
import org.softmed.rest.admin.aop.Aspect;

import com.google.inject.Inject;
import com.google.inject.name.Named;

public class AOPFacade {
	@Inject
	static AOPManager aopManager;

	@Inject
	static CustomActionManager customActionManager;

	
	@Inject
	AspectProvider aspectProvider;
	//TODO change this into an interface
	@Inject
	@Named("AspectProviderName")
	static String aspectProviderName;

	public static synchronized void refresh() throws Throwable {
		PersistenceManagerProvider ppm = new PersistenceManagerProvider(
				aspectProviderName);
		PersistenceManager util = ppm.getPersistenceManager();

		Object object = null;
		try {
			util.connect();

			aopManager.getAspects().clear();
			customActionManager.clearCaches();

			List list = util.getObjects(Aspect.class);

			aopManager.getAspects().addAll(list);
			List<Aspect> temp = new ArrayList<Aspect>();
			temp.addAll(aopManager.getAspects());

			for (Aspect aspect : temp) {
				if (!aspect.isActive())
					aopManager.getAspects().remove(aspect);
			}

			util.close();

		} catch (Throwable t) {
			t.printStackTrace();
			// TODO set the response with an error
			try {
				util.rollback();
				util.close();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			throw t;
		}
	}

	public static CustomActionManager getCustomActionManager() {
		return customActionManager;
	}

	public static void setCustomActionManager(
			CustomActionManager customActionManagerA) {
		customActionManager = customActionManagerA;
	}

	public static AOPManager getAopManager() {
		return aopManager;
	}

	public static void setAopManager(AOPManager aopManagerA) {
		aopManager = aopManagerA;
	}

}
